import {
  ACCESS_TOKEN, ACCESS_TOKEN_EXPIRES_IN,
  REFRESH_TOKEN, REFRESH_TOKEN_EXPIRES_IN,
  LAST_REQUEST_TIME
} from '@/store/mutation-types'
import { getCache, setCache, removeCache } from '../cacheUtils/cache'

// 缓存配置常量
const CACHE_CONFIG = {
  [ACCESS_TOKEN]: { expires: 2 * 60 * 60 * 1000 }, // 2小时
  [REFRESH_TOKEN]: { expires: 5 * 60 * 60 * 1000 } // 5小时
}

// 辅助函数
const getCacheByKey = (key) => getCache(key)

const setCacheByKey = (key, value) => {
  const config = CACHE_CONFIG[key] || {}
  setCache(key, value, config)
  setCache(`${key}_timestamp`, Date.now()) // 设置缓存时记录时间戳
}

const removeCachePair = (key) => {
  removeCache(key)
  removeCache(`${key}_timestamp`) // 删除缓存时删除时间戳
}

// 获取令牌
export const getAccessToken = () => getCacheByKey(ACCESS_TOKEN) // 获取访问令牌
export const getAccessTokenExpiresIn = () => getCacheByKey(ACCESS_TOKEN_EXPIRES_IN) // 获取访问令牌过期时间
export const getRefreshToken = () => getCacheByKey(REFRESH_TOKEN) // 获取刷新令牌
export const getRefreshTokenExpiresIn = () => getCacheByKey(REFRESH_TOKEN_EXPIRES_IN) // 获取刷新令牌过期时间
export const getLastRequestTime = () => getCacheByKey(LAST_REQUEST_TIME) // 获取最后请求时间

// 设置令牌
export const setAccessToken = (value) => setCacheByKey(ACCESS_TOKEN, value) // 设置访问令牌
export const setAccessTokenExpiresIn = (value) => setCacheByKey(ACCESS_TOKEN_EXPIRES_IN, value) // 设置访问令牌过期时间
export const setRefreshToken = (value) => setCacheByKey(REFRESH_TOKEN, value) // 设置刷新令牌
export const setRefreshTokenExpiresIn = (value) => setCacheByKey(REFRESH_TOKEN_EXPIRES_IN, value) // 设置刷新令牌过期时间
export const setLastRequestTime = (value) => setCacheByKey(LAST_REQUEST_TIME, value) // 设置最后请求时间

// 移除令牌
export const removeAccessToken = () => removeCachePair(ACCESS_TOKEN) // 移除访问令牌及其时间戳
export const removeAccessTokenExpiresIn = () => removeCachePair(ACCESS_TOKEN_EXPIRES_IN) // 移除访问令牌过期时间及其时间戳
export const removeRefreshToken = () => removeCachePair(REFRESH_TOKEN) // 移除刷新令牌及其时间戳
export const removeRefreshTokenExpiresIn = () => removeCachePair(REFRESH_TOKEN_EXPIRES_IN) // 移除刷新令牌过期时间及其时间戳
export const removeLastRequestTime = () => removeCachePair(LAST_REQUEST_TIME) // 移除最后请求时间及其时间戳

/**
 * 清除所有与令牌相关的缓存
 */
export const clearTokenCache = () => {
  const baseKeys = [
    LAST_REQUEST_TIME,
    ACCESS_TOKEN,
    ACCESS_TOKEN_EXPIRES_IN,
    REFRESH_TOKEN,
    REFRESH_TOKEN_EXPIRES_IN
  ]
  
  // 生成所有需要移除的键（基础键 + 它们的时间戳）
  const keysToRemove = baseKeys.flatMap(key => [key, `${key}_timestamp`])
  
  keysToRemove.forEach(removeCache) // 清除所有缓存
}